<?php
namespace control;
// 资产盘点
class assetInventoryClass extends adIndexClass
{
	private const page    = 'assetInventory';         # 权限
	private const table   = 'asset_inventory';        # 数据表
	private const tableMx = 'asset_inventory_detail'; # 子表
	private const title   = '资产盘点';
	public static array $inventoryState = ['已盘点','未盘点'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "盘点单号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '盘点名称',
                        'width' => 300,
                    ],
                    'stid'         => [
                        'name'  => '制单人',
                        'width' => 300,
                    ],
                    'time'          => [
                        'name'  => '盘点日期',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "盘点单号" => text(array("name" => "orderNo")),
                    "盘点名称" => text(array("name" => "name")),
                    "制单人" => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    "盘点日期" => text(
                        [
                            'name' => 'date',
                            'laydate' => ['range' => '~', 'type' => 'date'],
                        ]
                    ),
                    "状态" => select(["name" => "state", 'option' => ['制单', '审核中','已通过']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*固定资产入口页*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $root   = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&acid=' . $this->post('objId');
            $button .= "
			<span class='spanButton' onclick=\"newIframe('新建盘点','" . $root . "')\">新增</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportAll' class='spanButton'>导出</a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*固定资产列表*/
	public function homeSearch()
	{
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'name' => $this->post('name'),
			'coid' => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
			'stid'    => $this->post('stid'),
			'state'   => $this->post('state'),
		];
		//生成查询语句

		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('date')) {
			$where .= self::timeComparison($this->post('date'));
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => "固定盘点详情", "click" => "newIframe('固定盘点详情','" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $array['id'] . "')"],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    case 'time':
                        $row[] = self::formatDate($array['time']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	public function editPage()
	{
	    $id = $this->get('id')?:suiji();
		$info         = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditPageForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $tr[] = ['', '固定资产编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '盘点状态', '备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $index=>$array) {
            $asset  =query('asset',"id = '$array[atid]'");
            $tr[] = [
                componentClass::tablePperation($index+1,"deleteL(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])).
                hidden(array('name' => 'atid[]', 'value' => $array['atid'])).
                hidden(array('name'=>'num[]','value'=>$array['num'])),
                $asset['orderNo'],
                $asset['name'],
                $asset['brand'],
                $asset['model'],
                departmentClass::getTypeName($asset['departmentId']),
                self::findStaff($asset['user']),
                $asset['storage'],
                select(array('name' => 'inventoryState[]','option'=>self::$inventoryState, 'title' => '请选择', 'value' => $array['state'])),
                text(array('name'=>'mxText[]','value'=>$array['text']))
            ];
        }
        $total_tr = [
            3 => "<span id='total'>-</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true));
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '盘点名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    '使用人部门' => selectMultiple(["name" => "department", 'table' => "department", 'sqlId' => 'id', 'sqlField' => 'name', 'where' => " 1=1 ", 'title' => '领用人部门', 'value' => $info['department']]),
                    '分类(大类)' => selectMultiple(["name" => "classify", 'table' => "asset_catalog", 'sqlId' => 'name', 'sqlField' => 'name', 'where' => " pid = '0'", 'title' => '分类', 'value' => $info['classify']]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => "<span class='smallButton' onclick='getInventory()'>获取账面库存</span>",
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
            'hidden'=>hidden(array('name'=>'id','value'=>$id)),
		]);
        $data['html'] .= $this->js();
		//返回
		return $this->tab($data);
	}
    /**
     * JS
     * @return string
     */
    public function js(): string
    {
        return <<<eof
<script>
function getInventory(){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getInventory',$("form[name='assetInventoryEditPageForm']").serialize(),function(res) {
             if (res.warn ==2){
                $("#materialTable tbody").empty().append(res.html);
                $("#total").html('合计：'+res.total);
                resetNumber($("#materialTable tbody"))
           }else{
               msg(res.warn,'error');
           }
            
        },'json');
}

function deleteL(e){
    delTableRow(e);
    re_list();
}
    /**排序**/
    function re_list(){
        let total = 0;
        $("#materialTable tbody tr").each(function(index) {
           //$(this).find(".mx_list").html(index+1);
           total+=Number($(this).find("[name='num[]']").val());
        })
        $("#total").html('合计：'+total);
    }
</script>
eof;

    }
	/*基本资料新增或修改-异步处理*/
	public function editPageEdit()
	{
        $mxIdArr = $this->post('mxId');
        $atidArr = $this->post('atid');
        $inventoryStateArr = $this->post('inventoryState');
        $mxTextArr = $this->post('mxText');
        $numArr = $this->post('num');
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'name'       => $this->post('name'),
			'department' => $this->post('department'),
			'classify'   => $this->post('classify'),
			'text'       => $this->post('text'),
		];
		$annotation = [
			'name'       => '盘点名称',
			'department' => '领用人部门',
			'classify'   => '分类',
			'text'       => '备注',
		];
		$rules      = [
			'name' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		//判断
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif($info['id'] && $info['state'] !='制单'){
		    $json['warn'] = '此单据不是制单状态，不能编辑';
        }else {
		    $this->startTrans();
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'table'   => self::table,
                    'prefix'  => 'ZCPD' . date('Ymd'),
                    'default' => '001',
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'coid'    => self::$coid,
					'orderNo' => $orderNo,
					'state'   => '制单',
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'atid' => $atidArr[$k],
                            'state' => $inventoryStateArr[$k],
                            'text' => $mxTextArr[$k],
                            'num'=>$numArr[$k]?:0
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'atid' => $atidArr[$k],
                            'state' => $inventoryStateArr[$k],
                            'text' => $mxTextArr[$k],
                            'num'=>$numArr[$k]?:0
                        ],

                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
			    $this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . ($field['name'] ? "，盘点名称【{$field['name']}】" : '');
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}else{
			    $this->rollback();
            }
		}

		resp:
		return json_encode($json, 320);
	}
    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '制单' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name"  => '提交审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                'style' => 'li-btn-blue-bg',
                "post"  => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name'    => '资产盘点',
                        'table'   => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            // 保存函数
                            'save'   => [
                                'cla' => $this->get('cla'),
                                'fun' => 'editPageEdit',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after'  => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name"  => '审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                // 以下参数固定格式
                "post"  => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table'   => self::table,
                        // 当前状态
                        'state'   => $info['state'],
                        // 变更
                        'field'   => ['state'],   //变更字段 可多个
                        'value'   => [
                            'state' => ['制单', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after'  => [
                                'cla'  => $this->get('cla'),
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] == '审核中') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table'   => self::table,
                        // 当前状态
                        'state'   => $info['state'],
                        // 变更
                        'field'   => ['state'],   //变更字段 可多个
                        'value'   => [
                            'state' => ['制单'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
//								'fun' => 'cancelFun',
//                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }
	public function detail()
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看权限";
		} elseif (!$this->get('id')) {
			$html = "ID为空";
		} elseif (!$info['id']) {
			$html = "未找到此信息";
		} else {
			$data = [
				"id" => $info['id'],
			];
			//按钮
			$button = [];
            $button = array_merge($button, $this->auditButton($info));
            if ($info['state'] == '制单') {
                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑用户",
                        "url"   => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

			// 子表
			$mxtr[]   = ['固定资产编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '盘点状态', '备注'];
			if ($info['id']) {
				//订单明细
				$all = self::sqlFind("SELECT * FROM " . self::tableMx . " WHERE orderId = '$info[id]' ORDER BY list ");
				foreach ($all as $array) {
					$asset    = query('asset', " id = '{$array['atid']}' ");
					$mxtr[]   = [
						$asset['orderNo'],
						$asset['name'],
						$asset['brand'],
						$asset['model'],
						$asset['userDepartment'],
						self::findStaff($asset['user']),
						$asset['storage'],
                        $array['state'],
						$array['text']
					];
				}
			}
			// 生成子表单页面
            $exportBtn = '';
            if ($this->power(self::page, "export")) {
                $exportUrl = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=exportData&id=' . $info['id'];
                $exportBtn = "<span class='smallButton' onclick=\"window.location.href='$exportUrl'\">导出</span>";
            }
			$detailHtml = $this->listTable(['tr' => $mxtr,'showSort'=>true]);

			//按类别汇总
            $classifyTr[] = ['资产类别','账面数量','实盘数量','盘盈(盘亏)'];
            $all = find(array('table'=>'asset_catalog','where'=>"pid = '0' and coid = '".self::$coid."'"));
            foreach ($all['array'] as $array){
                $classifyArr = assetManagementClass::catalogCollection($array['id']);
                $children = find(array('table'=>'asset_inventory_detail as a join asset as b on a.atid = b.id','field'=>"ifnull(sum(b.num),0) as total",'single'=>"b.acid in ('".implode("','",$classifyArr)."')"));

                $childrenFact = find(array('table'=>'asset_inventory_detail as a join asset as b on a.atid = b.id','field'=>"ifnull(sum(b.num),0) as total",'single'=>"b.acid in ('".implode("','",$classifyArr)."') and a.state = '已盘点'"));
                $state = '正常';
                if ($children['total'] > $childrenFact['total']){
                    $state = '盘亏';
                }
                if ($children['total'] >0){
                    $classifyTr[] = [
                        $array['name'],
                        $children['total'],
                        $childrenFact['total'],
                        $state,
                    ];
                }

            }

            // 盘亏明细(未盘点的)
            $loss[]   = ['固定资产编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '备注'];
            if ($info['id']) {
                //订单明细
                $all = self::sqlFind("SELECT * FROM " . self::tableMx . " WHERE orderId = '$info[id]' and state = '未盘点' ORDER BY list ");
                foreach ($all as $array) {
                    $asset    = query('asset', " id = '{$array['atid']}' ");
                    $loss[]   = [
                        $asset['orderNo'],
                        $asset['name'],
                        $asset['brand'],
                        $asset['model'],
                        $asset['userDepartment'],
                        self::findStaff($asset['user']),
                        $asset['storage'],
                        $array['text']
                    ];
                }
            }
            // 生成子表单页面
            $url = $this->root.'control/adIndex.html?cla=assetCut&fun=editPage&sourceId='.$info['id'];
            $btn = '';
            if ($info['state'] =='已通过' && static::total(array('table'=>self::tableMx,'where'=>"id not in (select sourceId from asset_cut_detail where coid = '".self::$coid."' and sourceTable = 'asset_inventory_detail') and state = '未盘点'")) >0){
                $btn = "<span class='smallButton' onclick=\"newIframe('资产处置','{$url}')\">生成处置单</span>";
            }
            $lossHtml = $this->listTable(['tr' => $loss,'showSort'=>true]);
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				 [
					[
						"盘点单号"  => $info['orderNo'],
						"盘点名称"  => $info['name'],
						"使用人部门" => $info['department'],
                        "分类(大类)" => $info['classify'],
					],
					[
						"制单人"    => self::findStaff($info['stid']),
						"制单时间"   => $info['time'],
						"盘点完成时间" => $info['passTime'],
						"状态"     => $info['state'],
					],
				],

			]);
            $data['html'] .= $this->detailList([
                'title' => '固定资产清单',
                'button' => $exportBtn,
                'html' => $detailHtml,
            ]);
            $data['html'] .= $this->detailList([
                'title' => '盘点结果汇总(按类别)',
                'html' => $this->listTable(['tr'=>$classifyTr,'showSort'=>true]),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '盘亏明细',
                'button' => $btn,
                'html' => $lossHtml,
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

    /**
     * @param $id
     * @return array
     */
	public function getChildrenId($id){
        $result[] =$id;
        $all = find(['table'=>'asset_catalog','where'=>"pid = '$id'"]);
        foreach ($all['array'] as $array){
            $res = $this->getChildrenId($array['id']);
            $result = array_merge($result,$res);
        }
        return $result;
    }
	/**
	 * 导入所有
	 */
	public function getInventory(): bool|string
    {
		// 当领用人部门不为空时,查询该部门的领用记录
		$departmentId   = $this->post('department');
		$classify = $this->post('classify');
		$asset_catalog = query('asset_catalog',"name = '$classify' and coid = '".self::$coid."'");
		$asset_catalog_id = $this->getChildrenId($asset_catalog['id']);
        $where='';
		if (!empty($departmentId)) {
			$where .= " and departmentId = '$departmentId'";
		}
        if (!empty($classify)) {
            $where .= " and acid in ('".implode("','",$asset_catalog_id)."') ";
        }
		$result = find([
			'table' => 'asset',
			'where' => "state != '已处置' and coid = '" . self::$coid . "' ".$where,
		]);
		$tr = [];
		$totalNum = 0;
		foreach ((array)$result['array'] as $index=>$value) {
            $totalNum+=$value['num'];
            $tr[] = [
                componentClass::tablePperation('',"deleteL(this)").
                hidden(array('name' => 'mxId[]', 'value' => suiji())).
                hidden(array('name' => 'atid[]', 'value' => $value['id'])).
                hidden(array('name'=>'num[]','value'=>$value['num'])),
                $value['orderNo'],
                $value['name'],
                $value['brand'],
                $value['model'],
                departmentClass::getTypeName($value['departmentId']),
                self::findStaff($value['user']),
                $value['storage'],
                select(array('name' => 'inventoryState[]','option'=>self::$inventoryState, 'title' => '请选择', 'value' => '已盘点')),
                text(array('name'=>'mxText[]'))
            ];
		}
        $json['html'] = $this->tableMany(['tr'=>$tr,'thead'=>false]);
		$json['total'] = $totalNum;
		$json['warn'] = 2;
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = false; // 需要密码
		$form   = $power = $word = '';
		$append = [];
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'isDelete';
				$form     = self::page . 'OperateForm, listForm';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'append'   => $append,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	// 确认删除信息
	public function isDelete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 判断field
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['state'] !='制单'){
                    //添加记录
                    $text .= "{$this->control['name']}删除" . self::title . "：ID【{$id}】,名称【{$info['name']}】失败：不是制单状态<br>";
                }else{
                    // 删除子表
                    delete([
                        "table" => self::table . '_detail',
                        "where" => " orderId = '$id' ",
                    ]);
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where,
                    ]);
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog","where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message","where" => " typeid = '$id' "));
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】,名称【{$info['name']}】<br>";
                    $x++;
                }
			}

			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
		$id = $this->get('id');
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
		} elseif (empty($id)) {
			$_SESSION['warn'] = '参数不能为空';
		} else {
			$data   = [];
			$info   = query(self::table, " id = '$id' ");
			$where  = " orderId = '$id' ";
			$title  = ['盘点名称', '盘点单号', '固定资产编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '盘点状态', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => $where . ' order by time desc'));
			if (is_array($result['array'])) {
				foreach ($result['array'] as $array) {
					$asset  = query('asset', " id = '{$array['atid']}' ");
					$data[] = [
						$info['name'], $info['orderNo'], $asset['orderNo'], $asset['name'], $asset['brand'], $asset['model'], departmentClass::getTypeName($asset['departmentId']), self::findStaff($asset['user']), $asset['storage'], $array['state'], $array['text'],
					];
				}
			}
			$text = $this->control['name'] . "导出了" . self::title;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, '盘点单【'.$info['name']. "】盘点明细.xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}

    /**
     * 导出
     */
    public function exportAll()
    {

        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data   = [];
            $sql = $_SESSION[self::page]['sql'];
            $title  = ['盘点名称', '盘点单号', '固定资产编码', '名称', '品牌', '规格型号', '使用人部门', '使用人', '存放地点', '盘点状态', '备注'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $all = find(array('table'=>self::tableMx,'where'=>"orderId = '$array[id]' order by list"));
                    foreach ($all['array'] as $value){
                        $asset  = query('asset', " id = '{$value['atid']}' ");
                        $data[] = [
                            $array['name'], $array['orderNo'], $asset['orderNo'], $asset['name'], $asset['brand'], $asset['model'], departmentClass::getTypeName($asset['departmentId']), self::findStaff($asset['user']), $asset['storage'], $value['state'], $value['text'],
                        ];
                    }
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
